import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import { createPage, base, toast } from 'nc-lightapp-front';
import "./index.less"
import _, { get } from 'lodash';
const { NCPopover, NCButton, NCModal, NCRadio } = base;
const NCRadioGroup = NCRadio.NCRadioGroup;
const Tooltip = base.NCTooltip;
const Button = base.NCButton;
const { NCFormControl } = base;

/**
 * @功能: 单个数据行组件
 * @作者：Mr.sha
 * @日期：2022-05-27
 */
export default class DataTable extends Component {

    /**
     * @功能: 构造函数~~~一些初始化操作
     * @作者：Mr.sha
     * @日期：2022-05-27
     * @param {*} props 
     */
    constructor(props){
        super(props);
        let multiLang = null;
        if(this.props && this.props.MutiInit && this.props.MutiInit.getIntl){
            multiLang = this.props.MutiInit.getIntl(2011); 
        }
        this.state = {
            // 票袋名称
            tagName: multiLang.get('201103INUP-0019'),
            // 票袋名称的输入框是否只读
            readOnly: true,
            // 是否显示删除的modal
            showModal: false,

            // 是否显示 编辑、删除按钮
            showNCPopover: false,
            // 是否修改了当前对象
            isEdited: false,
            // 删除票袋时候的删除方式：只删除票袋(deleteBag)，删除票袋和发票（deleteAll）
            deleteType: "deleteAll",
            // 原来的数据
            initValue: null,
            // 票袋名称的最大值
            bagnameMaxLenght: 20,
            // 编辑框 是否鼠标移入 
            onMouseEnterNCPopover: false


        }
    }

    getMultiLang(){
        let multiLang = {};
        if(this.props && this.props.MutiInit && this.props.MutiInit.getIntl){
            multiLang = this.props.MutiInit.getIntl(2011); 
        }
        return multiLang;
    }

     
    //===================================================================================当前页面js函数~~~开始
    
    // 组件挂载完成触发的函数~~~只执行一次
    componentDidMount(){
        if(this.props && this.props.onDataTableRef){
            this.props.onDataTableRef(this)
        }  
    }

    /**
     * @功能: 获取整体div的class
     * @作者：Mr.sha
     * @日期：2022-05-27
     * @param {*} e 
     */
    handleAllGetClass() {
        let classArr = ['data-table'];
        let pk_erminvoice_bag = this.getIdAndName(this.props.item, "invoiceBag", "pk_erminvoice_bag");
        if(_.isEmpty(pk_erminvoice_bag) || pk_erminvoice_bag === ""){
            pk_erminvoice_bag = this.props.index;
        }
        if(this.props.activeId === pk_erminvoice_bag){
            classArr.push("data-table-active");
        }
        return classArr.join(" ");
    }


    /**
     * @功能: 获取整体div的class
     * @作者：Mr.sha
     * @日期：2022-05-27
     * @param {*} e 
     */
    handleAutoFocus() {
        let isAutoFocus = false;
        let pk_erminvoice_bag = this.getIdAndName(this.props.item, "invoiceBag", "pk_erminvoice_bag");
        if(_.isEmpty(pk_erminvoice_bag) || pk_erminvoice_bag === ""){
            pk_erminvoice_bag = this.props.index;
        }
        if(this.props.activeId === pk_erminvoice_bag && !this.state.readOnly){
            isAutoFocus = true;
        }
        return isAutoFocus;
    }


    /**
     * @功能: 票袋名称值改变触发的事件
     * @作者：Mr.sha
     * @日期：2022-05-27
     * @param {*} value
     */
    handleChangeDataTable(value) {

        // 票袋名称
        let bagname = this.getIdAndName(this.props.item, "invoiceBag", "bagname");
        if(!this.state.isEdited && !_.isEmpty(bagname)){
            this.setState({initValue: bagname});
        }
        let isCouldEdit = this.validateLength(value);
        // 改变数据并且更改修改的状态
        if(this.props && this.props.handleChangeDataTable && isCouldEdit){
            let pk_erminvoice_bag = this.getIdAndName(this.props.item, "invoiceBag", "pk_erminvoice_bag");
            let newValue = value;
            let index = this.props.index;
            let ininValue = _.isEmpty(this.state.initValue)? bagname : this.state.initValue;
            let params = {index, newValue, pk_erminvoice_bag, ininValue};
            this.props.handleChangeDataTable(params);
        }
        this.setState({isEdited: true});
    }

    /**
     * @功能: 票袋名称input框移除光标触发的事件~~~~保存数据
     * @作者：Mr.sha
     * @日期：2022-05-27
     * @param {*} value
     */
    handleBlurDataTable(value) {
        if(this.state.isEdited && this.props && this.props.handleEditDataTableList){
            // 票袋名称
            let bagname = this.getIdAndName(this.props.item, "invoiceBag", "bagname");
            if(_.isElement(bagname) || bagname === ""){
                let pk_erminvoice_bag = this.getIdAndName(this.props.item, "invoiceBag", "pk_erminvoice_bag");
                let newValue = _.isEmpty(this.state.initValue)? bagname : this.state.initValue;
                let index = this.props.index;
                let ininValue = _.isEmpty(this.state.initValue)? bagname : this.state.initValue;
                let params = {index, newValue, pk_erminvoice_bag, ininValue};
                this.props.handleChangeDataTable(params);
                const multiLang = this.getMultiLang(); 
                toast({ color: 'warning', content: multiLang.get('201103INUP-0018')});
            }
            else{
                this.props.handleEditDataTableList({dataTableObj: this.props.item, index: this.props.index});
            }
        }
        this.setState({readOnly: true ,isEdited: false, showNCPopover: false});
    }

    /**
     * @功能: 点击编辑按钮触发的事件
     * @作者：Mr.sha
     * @日期：2022-05-27
     * @param {*} e 
     */
    handleEditDataTable() {
        this.setState({readOnly: false});
        this.changeNCPopoverStatus();
    }
  
    /**
     * @功能: 点击删除按钮触发的事件
     * @作者：Mr.sha
     * @日期：2022-05-27
     * @param {*} e 
     */
    handleDeleteDataTable() {
        this.changeNCPopoverStatus();
        this.setState({
            showModal: true
        });

    }

    changeNCPopoverStatus() {
        setTimeout(()=>{
            this.setState({
                showNCPopover: !this.state.showNCPopover
            });
        },20);

    }


    getHandleNCPopoverHtml(){
        return (
            <NCPopover
                className = 'data-table-option' 
                content={this.nCPopoverContentDataTable()} 
                trigger="click" placement="bottom"
                show = {this.state.showNCPopover}
            >
                <NCButton
                    // onMouseLeave = {()=>{
                    //     this.setState({showNCPopover: false});
                    // }}
                className = "data-table-operation" onClick={() => {this.changeNCPopoverStatus()}}></NCButton>
            </NCPopover>
        )
    }


    closeDeleteModal() {
        this.setState({
            showModal: false
        });
    }

    confirmDeleteModal() {
        // deleteType	string	必须 删除方式：只删除票袋(deleteBag)，删除票袋和发票（deleteAll）	
        // pk_erminvoice_bag	string	必须 票袋pk
        let pk_erminvoice_bag = this.getIdAndName(this.props.item, "invoiceBag", "pk_erminvoice_bag");
        let params = {
            deleteType: this.state.deleteType,
            pk_erminvoice_bag,
            index: this.props.index
        };
        this.closeDeleteModal();
        this.props.handleDeleteDataTableList(params);
    }

    /**
     * @功能: 点击当前对象触发的事件
     * @作者：Mr.sha
     * @日期：2022-05-27
     * @param {*} e 
     */
    handleClickDataTable() {
        // 当前活动主键
        let activeId = this.getIdAndName(this.props.item, "invoiceBag", "pk_erminvoice_bag");
        if(_.isEmpty(activeId) && activeId === ""){
            activeId = this.props.index;
        }
        let params = { activeId } ;
        if(this.props && this.props.handleChangeActiveDataTableList){
            this.props.handleChangeActiveDataTableList(params);
        }
        
    }

    deleteRadioChange(e) {
        // 删除票袋时候的删除方式：只删除票袋(deleteBag)，删除票袋和发票（deleteAll）
        let deleteTypeValOld = this.state.deleteType;
        let deleteTypeValNew = "deleteAll";
        if(deleteTypeValOld === "deleteAll") {
            deleteTypeValNew = "deleteBag";
        }
        this.setState({deleteType: deleteTypeValNew})
    }

    //===================================================================================当前页面js函数~~~结束




    //===================================================================================当前页面界面布局~~~开始
    /**
     * @功能: 票单操作界面
     * @作者：Mr.sha
     * @日期：2022-05-27
     * @returns 
     */
    nCPopoverContentDataTable() {
        let multiLang =  this.getMultiLang();
        return (
            <div onMouseLeave = {
                ()=>{
                    this.setState({showNCPopover: false, onMouseEnterNCPopover: false});
                }}// onMouseEnterNCPopover onMouseLeaveNCPopover
                onMouseEnter = {() => {
                    this.setState({onMouseEnterNCPopover: true});
                }}
            >
                <div className = 'data-table-edit' 
                    onClick = {()=>{
                        this.handleEditDataTable();
                    }}
                >{ multiLang.get('201102SQFY-0020') }</div>
                
                <div className = 'data-table-delete'
                    onClick={()=>{
                        this.handleDeleteDataTable();
                    }} 
                >{ multiLang.get('2011-0004') }</div>
            </div>
        );
    }

    getDeleteModalHtml() {
        let multiLang = this.getMultiLang();
        return (
            <div>
                <NCModal size="sm" show={this.state.showModal} onHide={() => {this.closeDeleteModal()}}>
                    <NCModal.Header closeButton>
                        <NCModal.Title>{ multiLang.get('2011-0020') }</NCModal.Title>
                    </NCModal.Header>
            
                    <NCModal.Body>
                        <div className = 'delete-modal-main'>
                            <div class="delete-modal-icon"></div>
                            <div class="delete-modal-right">
                                <div class="delete-modal-title">{multiLang.get("201103INUP-0020") && multiLang.get("201103INUP-0020").replace("{bagname}",this.getIdAndName(this.props.item, "invoiceBag", "bagname"))}</div>
                                <div class="delete-modal-info">{multiLang.get("201103INUP-0022")}</div>
                                <NCRadioGroup
                                    name='basic'
                                    defaultValue = "deleteAll"
                                    onChange={() => {this.deleteRadioChange(this) }}
                                    selectedValue = {this.state.deleteType}
                                >
                                    <NCRadio value='deleteBag'>{multiLang.get("201103INUP-0023")}</NCRadio>
                                    <NCRadio value='deleteAll'>{multiLang.get("201103INUP-0024")}</NCRadio>
                                </NCRadioGroup>
                            </div>
                        </div>
                    </NCModal.Body>
            
                    <NCModal.Footer>
                        <NCButton onClick={() => {this.confirmDeleteModal()}} bordered>
                        {multiLang.get("2011-0003")} 
                        </NCButton> 
                        <NCButton onClick={() => {this.closeDeleteModal()}} colors="secondary" style={{ marginRight: 8 }}>
                        {multiLang.get("2011-0002")} 
                        </NCButton>
                    </NCModal.Footer>
                </NCModal>
            </div>
        );

    }

    /**
     * @功能: 获取ID和名称
     * @作者：Mr.sha
     * @日期：2022-06-01
     * @returns 
     */
    getIdAndName(item, startKey, endKey){
        let str = "";
        if(item && item[startKey] && item[startKey][endKey]){
            str = item[startKey][endKey];
        }
        return str;
    }

    /**
     * @功能: 显示票袋名称
     * @作者：Mr.sha
     * @日期：2022-06-08
     * @returns 
     */
    showTagName(){
        // 票袋名称
        let bagname = this.getIdAndName(this.props.item, "invoiceBag", "bagname");
        // 1、文件夹名称最多显示8个中文字符，超出7+…
        let bagnameLength = 0;
        
        if(!_.isEmpty(bagname)){
            bagnameLength = bagname.length;
        }
        if(bagnameLength > 8 && this.state.readOnly){
            bagname = bagname.substring(0,7) + "...";
        }
        return bagname;
    }

    /**
     * @功能: 获取其他信息
     * @作者：Mr.sha
     * @日期：2022-06-01
     * @returns 
     */
    getOnlyOneKey(item, key){
        let str = "";
        if(item && item[key]){
            str = item[key];
        }
        return str;
    }

    /**
     * @功能: 超出最大字符提示
     * @作者：Mr.sha
     * @日期：2022-06-16
     * @returns 
     */
    validateLength(value){
        let isCouldEdit = true;
        let multiLang = this.props.MutiInit.getIntl(2011);
        if (value.length > this.state.bagnameMaxLenght) {
            isCouldEdit = false;
            toast({
                mark: 'number_toast',
                color: 'danger',
                content: multiLang.get("validate-length") && 
                         multiLang.get("validate-length")
                         .replace("{maxLength}",this.state.bagnameMaxLenght)
                         // `最大录入长度为:${this.state.bagnameMaxLenght}`
            });
        }
        return isCouldEdit;
    }

    render() {

        let multiLang = this.props.MutiInit.getIntl(2011);
        
        let tip = (
			<div>
				{this.getIdAndName(this.props.item, "invoiceBag", "bagname")}
			</div>
		);

        return (
            <div className = {this.handleAllGetClass()}
            onClick={() => {this.handleClickDataTable()}}
            onMouseLeave = {()=>{
                this.setState({showNCPopover: false});
            }}
            >
                <div  className = "data-table-main">
                    <div className = "data-table-title">
                        <div className = "data-table-title-icon flex-col"></div>
                        <Tooltip inverse overlay={tip} placement = "right">
                            {/* <NCFormControl 
                                className = {['data-table-title-info', this.state.readOnly? "data-table-title-info-readonly" : ""].join(" ")}
                                placeholder='请输入票袋名称' 
                                id = {this.getIdAndName(this.props.item, "invoiceBag", "pk_erminvoice_bag")} // 票袋ID
                                value = {this.showTagName()} // 票袋名称
                                onChange = {this.handleChangeDataTable.bind(this)}
                                onBlur = {this.handleBlurDataTable.bind(this)}
                            /> */}
                            {

                                !this.state.readOnly && 
                                <NCFormControl
                                    className = {['data-table-title-info'].join(" ")}
                                    placeholder={multiLang.get("201103INUP-0028")}
                                    id = {this.getIdAndName(this.props.item, "invoiceBag", "pk_erminvoice_bag")} // 票袋ID
                                    value = {this.showTagName()} // 票袋名称
                                    onChange = {this.handleChangeDataTable.bind(this)}
                                    onBlur = {this.handleBlurDataTable.bind(this)}
                                    autoFocus = {this.handleAutoFocus()}
                              />
                            }
                            {this.state.readOnly && <div className = "data-table-title-info-readonly">{this.showTagName()}</div>}
                          
                              
                        </Tooltip>

                    </div>
                    <div className = "data-table-data">
                        {/* 总金额 */}
                        <span className = "data-table-data-money">¥{this.getOnlyOneKey(this.props.item, "invoicesum") }</span>
                        <div className = "data-table-data-icon">|</div>
                        {/* 数量 */} 
                        <span className = "data-table-data-count">
                            {
                                multiLang.get("201103INUP-0029") &&
                                multiLang.get("201103INUP-0029")
                                .replace("{count}",this.getOnlyOneKey(this.props.item, "count"))
                            }
                        </span>
                    </div>
                </div>
                <div>
                    {
                        this.getIdAndName(this.props.item, "invoiceBag", "pk_erminvoice_bag") !== "all" &&
                        this.getIdAndName(this.props.item, "invoiceBag", "pk_erminvoice_bag") !== "other" &&
                        this.getHandleNCPopoverHtml()
                    }
                </div>
                {/* <NCPopover className = 'data-table-option' content={this.nCPopoverContentDataTable()} trigger="click" placement="bottom">
                    <NCButton class="data-table-operation"></NCButton>
                </NCPopover> */}

                {this.getDeleteModalHtml()}
            </div>
        )
    }

    //===================================================================================当前页面界面布局~~~结束
}

DataTable = createPage({
    mutiLangCode: '2011'
})(DataTable);

ReactDOM.render(<DataTable />, document.querySelector('#app'))